<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/03/15
 * 描述:
 */

namespace app\result\auto;

use app\model\auto\RechargeLog;
use app\model\auto\RechargePackage;
use app\model\order\Order;
use app\model\user\User;
use app\result\BaseResult;
use app\result\order\OrderResult;
use app\service\CreditService;
use app\service\PaymentService;
use think\facade\Db;


class RechargeLogResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new RechargeLog();
    }


    // 表格列
    public function el_table_column(): array
    {
        return [
            ['prop' => 'money', 'type' => 'text', 'label' => '充值金额', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'gift_money', 'type' => 'text', 'label' => '赠送金额', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'order_sn', 'type' => 'text', 'label' => '订单编号', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'pay_type', 'type' => 'tags', 'label' => '支付方式', 'minWidth' => '120', 'align' => 'center',
                'tags' => [
                    1 => ['label' => '微信', 'color' => '', 'type' => 'success',],
                    2 => ['label' => '支付宝', 'color' => '', 'type' => 'primary',],
                    3 => ['label' => '转账', 'color' => '', 'type' => 'warning',],
                ]],
            ['prop' => 'pay_status', 'type' => 'tags', 'label' => '支付状态', 'minWidth' => '120', 'align' => 'center',
                'tags' => [
                    0 => ['label' => '待支付', 'color' => '', 'type' => 'warning',],
                    1 => ['label' => '已付款', 'color' => '', 'type' => 'success',],
                ]],
            ['prop' => 'check_status', 'type' => 'tags', 'label' => '审核状态', 'minWidth' => '120', 'align' => 'center',
                'tags' => [
                    0 => ['label' => '待审核', 'color' => '', 'type' => 'warning',],
                    1 => ['label' => '已审核', 'color' => '', 'type' => 'success',],
                    2 => ['label' => '已拒绝', 'color' => '', 'type' => 'danger',],
                ]],
            ['prop' => 'pay_time', 'type' => 'text', 'label' => '支付时间', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'trans_no', 'type' => 'text', 'label' => '交易号', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'created_at', 'type' => 'text', 'label' => '创建时间', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'updated_at', 'type' => 'text', 'label' => '修改时间', 'minWidth' => '120', 'align' => 'center',],
        ];
    }

    //列表搜索字段
    private function _searchField(): array
    {
        return [
            ['name' => 'order_sn', 'label' => '订单编号', 'type' => 'input', 'placeholder' => '订单编号',],
            ['name' => 'pay_type', 'label' => '支付方式', 'type' => 'select', 'placeholder' => '支付方式',
                'options' => [
                    1 => ['label' => '微信', 'value' => '1',],
                    2 => ['label' => '支付宝', 'value' => '2',],
                    3 => ['label' => '转账', 'value' => '3',],
                ]],
            ['name' => 'pay_status', 'label' => '支付状态', 'type' => 'select', 'placeholder' => '支付状态',
                'options' => [
                    0 => ['label' => '待支付', 'value' => '0',],
                    1 => ['label' => '已支付', 'value' => '1',]
                ]],
            ['name' => 'pay_time', 'label' => '支付时间', 'type' => 'datePicker', 'placeholder' => '支付时间',],
            ['name' => 'trans_no', 'label' => '交易号', 'type' => 'input', 'placeholder' => '交易号',],
            ['name' => 'created_at', 'label' => '创建时间', 'type' => 'datePicker', 'placeholder' => '创建时间',],
        ];
    }

    // 获取公共条件限制
    private function _where($args = []): array
    {
        $where = [];
        $keyword = trim($args['keyword'] ?? '');
        $pay_status = $args['pay_status'] ?? '';
        if ($keyword) {
            $where[] = ['order_sn|trans_no', 'like', '%' . trim($args['keyword']) . '%'];
        }

        if (is_numeric($pay_status)) {
            $where[] = ['pay_status', '=', $pay_status];
        }
        return $where;
    }

    public function list($args = []): array
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $sort_by = trim($args['sort_by'] ?? 'id desc');
        $where = $this->_where($args);
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', $sort_by, $page, $pageSize);
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data,
            'el_table_column' => $this->el_table_column(),
            'search_fields' => $this->_searchField()
        ]);
    }

    public function get($args = []): array
    {
        $id = intval($args['id'] ?? 0);
        $data = $this->model->data_get(["id" => $id]);
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        return $this->success_return('success', [
            'info' => $data
        ]);
    }

    public function api_ready($args = [])
    {
        $list = (new RechargePackage())->data_list_nopage(['status' => 1], '*', 'sort desc');
        return self::success_return('success', [
            'packages' => $list
        ]);
    }

    //历史记录
    public function api_history($user_id, $args = [])
    {
        $page = intval($args['page'] ?? 1);
        $limit = intval($args['limit'] ?? 20);
        $keywords = $args['keywords'] ?? '';
        $where = [['user_id', '=', $user_id]];
        if ($keywords) {
            $where[] = ['order_sn|trans_no', 'like', '%' . $keywords . '%'];
        }

        $order = 'id desc';

        $field = 'total_money,money,gift_money,pay_type,pay_status,check_status,pay_time,trans_no,order_sn,created_at';
        $data = $this->model->data_list($where, $field, $order, $page, $limit);
        if ($data) {
            foreach ($data as &$v) {
                $v['pay_type_desc'] = $this->pay_type_desc($v['pay_type']);
                $v['pay_status_desc'] = $this->pay_status_desc($v['pay_status']);
                $v['check_status_desc'] = $this->check_status_desc($v['check_status']);
            }
            unset($v);
        }
        return self::success_return('success', [
            'list' => $data
        ]);
    }

    public function api_detail($user_id, $args = [])
    {
        $order_sn = trim($args['order_sn'] ?? '');
        if (!$order_sn) {
            return self::error_return('订单编号不能为空');
        }
        $data = $this->model->data_get(['order_sn' => $order_sn, 'user_id' => $user_id]);
        if (!$data) {
            return self::error_return('订单不存在');
        }
        return self::success_return('success', [
            'info' => $data
        ]);
    }

    public function api_pay($user_id, $args = [])
    {
        $money = $args['money'] ?? 0;
        $pay_type = $args['pay_type'] ?? 1;
        $package_id = $args['package_id'] ?? 0;
        if (!$money && !$package_id) {
            return self::error_return('充值金额不能为空');
        }
        $gift_money = 0;
        if (!empty($package_id)) {
            $package = (new RechargePackage())->data_get(['id' => $package_id, 'status' => 1,]);
            if (!$package) {
                return self::error_return('充值套餐已下线');
            }
            $money = $package['money'];
            $gift_money = $package['gift_money'];
        } else {
            if ($money < 0.01) {
                return self::error_return('充值金额不能小于0');
            }
        }
        $order_sn = 'REC' . date('YmdHis');
        while (true) {
            if (!$this->model->data_get(['order_sn' => $order_sn])) {
                break;
            }
            $order_sn = 'REC' . date('YmdHis');
        }
        $totalMoney = $money + $gift_money;
        $data = [
            'order_sn' => $order_sn,
            'user_id' => $user_id,
            'money' => $money,
            'gift_money' => $gift_money ?? 0,
            'total_money' => $totalMoney,
            'pay_type' => $pay_type,
            'check_status' => 1
        ];
        $res = $this->model->data_add($data);
        if (!$res) {
            return self::error_return('创建订单失败');
        }
        if ($pay_type == 2) {
            $req = (new PaymentService())->alipay([
                'order_sn' => $order_sn,
                'order_amount' => $money,
                'subject' => '余额充值',
                'user_id' => $user_id,
            ]);
            $domain = request()->domain();
            return self::success_return('请求成功，请支付', [
                'order_sn' => $order_sn,
                'params' => $req,
                'url' => $domain . '/api/payment/cashier?order_sn=' . $order_sn . '&title=收银台&api_base_url=' . $domain . '&token=' . ($args['token'] ?? '')
            ]);
        } else if ($pay_type == 3) {
            try {
                Db::startTrans();
                $res = (new RechargeLog())->data_update(['order_sn' => $order_sn], [
                    'pay_time' => date('Y-m-d H:i:s'),
                    'pay_status' => 0,
                    'pay_type' => $pay_type,
                    'check_status' => 0,
                ]);
                if (!$res) {
                    throw new \Exception('转账支付保存失败');
                }
            } catch (\Exception $e) {
                Db::rollback();
                return self::error_return($e->getMessage());
            }
            Db::commit();
            return self::success_return('提交成功，等待后台审核', [
                'order_sn' => $order_sn,
            ]);
        } else {
            return self::error_return('暂不支持该支付方式');
        }
    }

    private function pay_type_desc($pay_type)
    {
        $pay_type_desc = [
            1 => '微信',
            2 => '支付宝',
            3 => '转账',
        ];
        return $pay_type_desc[$pay_type] ?? '其它';
    }

    private function pay_status_desc($pay_status)
    {
        $pay_status_desc = [
            0 => '待支付',
            1 => '已支付',
            2 => '已退款',
        ];
        return $pay_status_desc[$pay_status] ?? '其它';
    }

    private function check_status_desc($check_status)
    {
        $check_status_desc = [
            0 => '待审核',
            1 => '已审核',
            2 => '已拒绝',
        ];
        return $check_status_desc[$check_status] ?? '其它';
    }

    // 审核
    public function check($args)
    {
        $order_sn = trim($args['order_sn'] ?? '');
        $status = trim($args['check_status'] ?? '');
        $check_fail_reason = trim($args['check_fail_reason'] ?? '');
        if (!$order_sn) {
            return self::error_return('订单编号不能为空');
        }
        if (!in_array($status, [1, 2])) {
            return self::error_return('状态不正确');
        }
        if ($status == 2 && !$check_fail_reason) {
            return self::error_return('拒绝原因不能为空');
        }
        $data = $this->model->data_get(['order_sn' => $order_sn]);
        if (!$data) {
            return self::error_return('订单不存在');
        }
        if ($data['pay_status'] == 1) {
            return self::error_return('订单已支付');
        }
        $baseData = [
            'check_status' => $status,
            'check_fail_reason' => $check_fail_reason,
            'check_time' => date('Y-m-d H:i:s'),
        ];
        if ($status == 1) {
            $baseData['pay_status'] = 1;
        }
        Db::startTrans();
        try {
            $res = (new RechargeLog())->data_update(['order_sn' => $order_sn], $baseData);
            if (!$res) {
                throw new \Exception('审核失败');
            }
            if ($status == 1) {
                $res = (new CreditService())->credit_action($data['user_id'], $data['total_money'], [
                    'remark' => '转账充值',
                    'order_sn' => $order_sn,
                ]);
                if (!$res) {
                    throw new \Exception('充值失败');
                }
                if (config('point.open') && config('point.recharge')) {
                    $point = config('point.recharge');//1元1积分转换
                    $point = $data['total_money'] * $point;
                    if ($point >= 1) {
                        $pointAction = (new CreditService())->point_action($data['user_id'], $point, [
                            'order_sn' => $order_sn,
                            'remark' => '余额充值赠送'
                        ]);
                    }

                }
            }
            admin_log('审核充值订单：' . $order_sn . '，状态：' . $this->check_status_desc($status) . '，原因：' . $check_fail_reason, $data);
        } catch (\Exception $e) {
            Db::rollback();
            return self::error_return($e->getMessage());
        }
        Db::commit();
        return self::success_return('审核成功');
    }
}
